# 优化的rclone安装脚本
# 用于在Windows系统上安装rclone

param(
    [string]$InstallPath = "C:\Program Files\rclone"
)

Write-Host "开始安装rclone..."

# 检查是否以管理员权限运行
$isAdmin = ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")
if (-not $isAdmin) {
    Write-Host "警告: 请以管理员权限运行此脚本以确保正确安装" -ForegroundColor Yellow
}

try {
    # 获取系统架构
    $arch = $env:PROCESSOR_ARCHITECTURE
    Write-Host "系统架构: $arch"

    # 确定下载URL
    $downloadUrl = ""
    switch ($arch) {
        "AMD64" {
            $downloadUrl = "https://downloads.rclone.org/rclone-current-windows-amd64.zip"
            Write-Host "使用64位版本"
        }
        "x86" {
            $downloadUrl = "https://downloads.rclone.org/rclone-current-windows-386.zip"
            Write-Host "使用32位版本"
        }
        default {
            Write-Host "警告: 未知架构 $arch，使用64位版本作为默认值" -ForegroundColor Yellow
            $downloadUrl = "https://downloads.rclone.org/rclone-current-windows-amd64.zip"
        }
    }

    # 创建临时目录
    $tempDir = [System.IO.Path]::GetTempPath()
    $downloadPath = Join-Path $tempDir "rclone.zip"
    $extractPath = Join-Path $tempDir "rclone_extract"

    # 清理之前的临时文件
    if (Test-Path $downloadPath) {
        Remove-Item -Path $downloadPath -Force
    }
    if (Test-Path $extractPath) {
        Remove-Item -Path $extractPath -Recurse -Force
    }

    # 下载rclone
    Write-Host "下载rclone..."
    [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
    Invoke-WebRequest -Uri $downloadUrl -OutFile $downloadPath -UseBasicParsing

    # 检查下载是否成功
    if (-not (Test-Path $downloadPath)) {
        throw "下载失败: 文件未找到"
    }

    # 解压文件
    Write-Host "解压文件..."
    Expand-Archive -Path $downloadPath -DestinationPath $extractPath -Force

    # 获取解压后的目录名
    $rcloneDirs = Get-ChildItem -Path $extractPath -Directory | Where-Object { $_.Name -like "rclone-*-windows-*" }
    if ($rcloneDirs.Count -eq 0) {
        throw "无法找到解压后的rclone目录"
    }
    
    $rcloneDir = $rcloneDirs[0]
    Write-Host "找到目录: $($rcloneDir.Name)"

    # 创建安装目录
    Write-Host "安装rclone到 $InstallPath..."
    if (!(Test-Path $InstallPath)) {
        New-Item -ItemType Directory -Path $InstallPath -Force | Out-Null
    }

    # 复制二进制文件
    $sourceFile = Join-Path $rcloneDir.FullName "rclone.exe"
    if (-not (Test-Path $sourceFile)) {
        throw "rclone.exe未找到在 $sourceFile"
    }
    
    Copy-Item -Path $sourceFile -Destination $InstallPath -Force

    # 添加到系统PATH（仅在有管理员权限时）
    if ($isAdmin) {
        $envPath = [Environment]::GetEnvironmentVariable("Path", [EnvironmentVariableTarget]::Machine)
        if ($envPath -notlike "*$InstallPath*") {
            Write-Host "添加rclone到系统PATH..."
            [Environment]::SetEnvironmentVariable("Path", "$envPath;$InstallPath", [EnvironmentVariableTarget]::Machine)
            Write-Host "已将rclone添加到系统PATH"
        } else {
            Write-Host "rclone已在系统PATH中"
        }
    } else {
        Write-Host "提示: 请手动将 $InstallPath 添加到系统PATH环境变量" -ForegroundColor Yellow
    }

    # 清理临时文件
    Write-Host "清理临时文件..."
    Remove-Item -Path $downloadPath -Force -ErrorAction SilentlyContinue
    Remove-Item -Path $extractPath -Recurse -Force -ErrorAction SilentlyContinue

    # 验证安装
    Write-Host "验证安装..."
    $rclonePath = Join-Path $InstallPath "rclone.exe"
    if (Test-Path $rclonePath) {
        Write-Host "rclone.exe存在: $rclonePath"
        try {
            $versionInfo = & rclone --version 2>$null
            if ($LASTEXITCODE -eq 0 -and $versionInfo) {
                Write-Host "rclone版本信息:"
                $versionInfo | ForEach-Object { Write-Host $_ }
                Write-Host "rclone安装完成!" -ForegroundColor Green
                exit 0
            } else {
                Write-Host "警告: rclone可执行文件存在但无法运行" -ForegroundColor Yellow
                exit 1
            }
        } catch {
            Write-Host "警告: rclone可执行文件存在但无法运行: $($_.Exception.Message)" -ForegroundColor Yellow
            exit 1
        }
    } else {
        Write-Host "错误: rclone安装失败，文件未找到: $rclonePath" -ForegroundColor Red
        exit 1
    }
} catch {
    Write-Host "安装过程中出现错误: $($_.Exception.Message)" -ForegroundColor Red
    Write-Host "详细信息: $($_.Exception.ToString())" -ForegroundColor Red
    exit 1
}